using Enemy;
using UnityEngine;

public class EnemyCharacter : Character
{
    private Collider2D coll;
    private Rigidbody2D rb;

    // 重写生命值属性字段，更改生命值时同步更新敌人血条
    public override float CurrentHealth{
        get { return _currentHealth; }
        set{
            _currentHealth = value;
            //更新血条UI
            GetComponentInChildren<EnemyHealthBar>(true).UpdateHP(_currentHealth, maxHealth);
        }
    }

    [Header("击退")]
    public float knokbackForce = 2f;//击退力
    private Vector2 direction;//击退方向向量
    [Header("受击特效")]
    private Animator hitAnimator; // 敌人的受击特效动画控制器

    private void Awake()
    {
        coll = GetComponent<Collider2D>();
        rb = GetComponent<Rigidbody2D>();
        hitAnimator = transform.GetChild(0).GetComponent<Animator>();
    }

    // 受伤逻辑
    protected override void Hit(Attack attack)
    {
        GetComponent<Enemy.FSM>().parameter.isHurt = true;

        //击退
        rb.velocity = Vector2.zero;
        direction = (transform.position - attack.transform.parent.position).normalized;
        rb.AddForce(direction * knokbackForce, ForceMode2D.Impulse);

        // 播放受击特效动画
        hitAnimator.SetTrigger("isHit"); 
    }

    // 死亡逻辑
    protected override void Die()
    {
        EnemyManager.Instance.KillEnemy(transform);
        GetComponent<Enemy.FSM>().parameter.isDead = true;
        //取消碰撞
        coll.enabled = false;
        //生成战利品
        GetComponent<ItemSpawner>().DropItems();
        Destroy(gameObject, 2f);
    }

    public override void SetHealth(float value)
    {
        base.SetHealth(value);

        //伤害飘字
        Color color = value > 0 ? Color.blue : Color.red;
        string str = value > 0 ? "+" + value : "-" + value;
        GameManager.Instance.ShowText(str, transform.position, color);
    }
}